package org.yty.travelagencymongodb.service.impl;

import cn.hutool.core.util.IdUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.yty.travelagencymongodb.model.Entity.Guidebook;
import org.yty.travelagencymongodb.repository.GuidebookRepository;
import org.yty.travelagencymongodb.service.GuidebookService;

import java.time.LocalDateTime;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class GuidebookServiceImpl implements GuidebookService {
    private final GuidebookRepository guidebookRepository;
    private final MongoTemplate mongoTemplate;

    @Override
    public Guidebook getById(Long id) {
        Optional<Guidebook> option = this.guidebookRepository.findById(id);
        return option.isEmpty() ? null : option.get();
    }

    @Override
    public boolean save(Guidebook guidebook) {
        if (guidebook.getId() == null){
            guidebook.setId(IdUtil.getSnowflakeNextId());
        }
        guidebook.setCreateTime(LocalDateTime.now());
        guidebook.setUpdateTime(LocalDateTime.now());
        guidebook = this.guidebookRepository.insert(guidebook);
        return guidebook != null;
    }

    @Override
    public boolean update(Guidebook guidebook) {
        guidebook.setUpdateTime(LocalDateTime.now());
        guidebook = this.guidebookRepository.save(guidebook);
        return guidebook != null;
    }

    @Override
    public void removeById(Long id) {
        this.guidebookRepository.deleteById(id);
    }
}
